<!DOCTYPE html>
<meta charset="utf-8">
<style>
body{
  font-weight:bold;
}
.axis path, .axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

</style>
<body>
<script src="../../d3.js"></script>
<script>
//svg尺寸
var margin = {top: 20, right: 40, bottom: 40, left: 20},
    width = 500 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
//数据集
var dataset=[{"key":"猴子","value":20},{"key":"大象","value":13},{"key":"老虎","value":6},{"key":"长颈鹿","value":12}];
//线性比例尺
var linearScale=d3.scale.linear()  
             .domain([0,d3.max(dataset,function(d){ return d.value;})])    
             .range([0,height]); 
//序数比例尺
var ordinalScale  = d3.scale.ordinal()
	.domain(dataset.map(function(d){ return d.key;}))
    .range([0, 100,200,440]);
//创建svg标签
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + 0 + "," + margin.top + ")");
//创建矩形条
var rects=svg.selectAll("rect")
	.data(dataset)
	.enter()
	.append("rect")
	.attr({
		x:function(d){ return ordinalScale(d.key)+margin.left/2+5; },
		y:function(d,i){ return height-linearScale(d.value); },	//矩形起始纵坐标
		width:10,
		height:function(d){ return linearScale(d.value); },	//矩形的条高
		fill:function(d){ return "steelblue"; },
		stroke:'black',
		'stroke-width':.5
	});
//创建矩形条的文本
var texts=svg.selectAll("text")
	.data(dataset)
	.enter()
	.append("text")
	.text( function(d){ return d.value; })
	.attr({
		x:function(d){ return ordinalScale(d.key)+margin.left/2+5; },
		y:function(d,i){ return height-linearScale(d.value); }
	});
//创建坐标轴
svg.append("g")
 .attr("transform", "translate(" + margin.left + "," + height + ")")
    .attr("class", "x axis")
    .call(d3.svg.axis().scale(ordinalScale).orient("bottom"));

</script>